package thread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//import java.net.ConnectException;
//import java.io.ObjectInputStream;
//import java.net.SocketException;
import java.util.Calendar;
import java.util.Map;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

import analyser.ProtocolAnalyser;
import pojo.Protocol;
import processor.UpdateChatWin;
import processor.UpdateLoginWin;
import socket.ClientSocket;
import ui.WindowTypes;
import util.ProtocolJSONConverter;

public class ServerMsgHandler implements Runnable {
	
	private static final Logger LOGGER = Logger.getLogger(ServerMsgHandler.class);
	
	private Map<Integer, JFrame> windows;
	private ProtocolAnalyser analyser;

	public ServerMsgHandler(Map<Integer, JFrame> windows) {
		this.windows = windows;
		this.analyser = new ProtocolAnalyser(windows);
	}

	@Override
	public void run() {
		while (true) {
//			ObjectInputStream objIn = null;
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new InputStreamReader(ClientSocket.getInstance().getInputStream()));
			} catch (IOException e) {
//				e1.printStackTrace();
				LOGGER.error(e.toString());
				JOptionPane.showMessageDialog(windows.get(WindowTypes.LOGIN_WIN), "Connection failed!", "Error", JOptionPane.ERROR_MESSAGE);
				new UpdateLoginWin(windows.get(WindowTypes.LOGIN_WIN)).quit();
				break;
			}
			
			
			// resolve protocol
			Protocol readPro = null;
			try {
//				readPro = (Protocol) objIn.readObject();
				String line = reader.readLine();
				
				if (line == null) {
					// server crashed, notify client
					UpdateChatWin updateChatWin = new UpdateChatWin(windows.get(WindowTypes.CHAT_WIN));
					updateChatWin.nofityServerCrash(Calendar.getInstance().getTime());
					break;
				}else{
					readPro = ProtocolJSONConverter.toProtocol(line);
				}
				
			} catch (IOException e) {
//				e.printStackTrace();
				LOGGER.error(e.toString());
				if (e.getMessage().contains("Connection reset")) {
					// server crashed
					UpdateChatWin updateChatWin = new UpdateChatWin(windows.get(WindowTypes.CHAT_WIN));
					updateChatWin.nofityServerCrash(Calendar.getInstance().getTime());
					break;
				}
			}
			if (readPro == null) {
				continue;
			}
			
			// analyse protocol
			analyser.analyse(readPro);
		}
	}

}
